package com.lingyi.common.utils;

import okhttp3.OkHttpClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

/**
 * @PackageName: com.lingyi.common.utils
 * @ClassName: RestTemplateUtil
 * @Description:
 * @Author: czl
 * @Date: 2025/4/19 17:02
 */
@Component
public class RestTemplateUtil {

    private final RestTemplate restTemplate;

    @Bean
    public OkHttpClient okHttpClient() {
        return new OkHttpClient();
    }

    public RestTemplateUtil() {
        this.restTemplate = new RestTemplate();
    }

    /**
     * 发送GET请求
     *
     * @param url 请求URL
     * @return 响应实体
     */
    public ResponseEntity<String> sendGetRequest(String url) {
        try {
            return restTemplate.getForEntity(url, String.class);
        } catch (RestClientException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 发送POST请求
     *
     * @param url 请求URL
     * @param body 请求体
     * @return 响应实体
     */
    public ResponseEntity<String> sendPostRequest(String url, String body) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<String> requestEntity = new HttpEntity<>(body, headers);
        try {
            return restTemplate.postForEntity(url, requestEntity, String.class);
        } catch (RestClientException e) {
            e.printStackTrace();
            return null;
        }
    }
}
